<?php

use Medoo\Medoo;
use QL\QueryList;

/**
 * http://docs.guzzlephp.org/en/stable/request-options.html#query
 * https://medoo.in/api/new
 * http://www.querylist.cc/docs/guide/v4/http-client
 */
chdir(__DIR__);
require_once realpath('..') . '/vendor/autoload.php';
$config = include 'database.php';
const BRAND = '奔驰';

echo '爬虫开始' . PHP_EOL;
$db = new Medoo($config);
$db->delete('tDealer', ['sBrand' => BRAND]);
$client = new GuzzleHttp\Client();

function get_provinces()
{
    global $client;
    $res = $client->get(
        'https://api.oneweb.mercedes-benz.com.cn/ow-dealers-location/provinces/query?needFilterByDealer=true&needFilterByModel=false&modelName=null',
        [
            'headers' => [
                'User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36'

            ]
        ]);
    $html = (string)$res->getBody();

    $temp = json_decode($html, true);
    return $temp['result'];
}

function get_cities($province_id)
{
    global $client;
    $res = $client->get(
        "https://api.oneweb.mercedes-benz.com.cn/ow-dealers-location/cities/query?needFilterByDealer=true&provinceId={$province_id}&needFilterByModel=false&modelName=",
        [
            'headers' => [
                'User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36'

            ]
        ]);
    $html = (string)$res->getBody();

    $temp = json_decode($html, true);
    return $temp['result'];
}

function get_dealers($city_name)
{
    global $client;
    $res = $client->get(
        "https://api.oneweb.mercedes-benz.com.cn/ow-dealers-location/dealers/query?sort=alphabetical&city={$city_name}&longitude=&latitude=&keywords=&dealerId=&needFilterByModel=false&modelName=",
        [
            'headers' => [
                'User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36'

            ]
        ]);
    $html = (string)$res->getBody();

    $temp = json_decode($html, true);
    return $temp['result'];
}


$provinces = get_provinces();
foreach ($provinces as $p) {
    $province_id = $p['id'];
    $province_name = $p['name'];
    $cities = get_cities($province_id);
    foreach ($cities as $city) {
        $city_name = $city['name'];
        sleep(1);
        $dealers = get_dealers($city_name);

        foreach ($dealers as $item) {
            $remarks = '/';
            $services = $item['service_scope'];

            if (is_array($services) && count($services) > 0) {

                foreach ($services as $service) {

                    if (is_array($service) && $service['categoryCode'] === 'sales') {
                        $types = $service['types'];

                        $remarks = array_reduce($types, function ($all, $cur) {
                            return $all . '/' . $cur['name'];
                        });
                    }
                }
            }

            $db->insert('tDealer', [
                'sDealerName' => $item['displayName'],
                'nBrandID' => $item['dealerCode'],
                'sBrand' => BRAND,
                'sProvince' => $item['province'],
                'sCity' => $item['city'],
                'sAddress' => $item['address'],
                'sSaleCall' => $item['afterSaleServicePhoneNumber'],
                'sLatitude' => $item['latitude'],
                'sLongitude' => $item['longitude'],
                'dUpdateTime' => Medoo::raw('now()'),
                'sManufacturer' => BRAND,
                'sRemarks' => $remarks,
            ]);
            echo "{$item['displayName']}完成" . PHP_EOL;
        }
    }
}
echo '爬虫结束' . PHP_EOL;